package com.baofu.paycore.service.validate.impl.preAuth;

import com.baofu.paycore.common.exception.PayCoreBizException;
import com.baofu.paycore.manager.model.PayBaseBO;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.manager.model.preAuth.PreAuthBO;
import com.baofu.paycore.manager.storer.PreAuthRepository;
import com.baofu.paycore.service.facade.enums.PayStatusEnums;
import com.baofu.paycore.service.facade.model.CancelPayDTO;
import com.baofu.paycore.service.validate.AbstractPayValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 预授权撤销校验
 *
 * User: xin deng  Date: 16/8/31 ProjectName: paycore Version: 1.0
 */
@Slf4j
@Service
public class PreAuthCancelValidate extends AbstractPayValidate<CancelPayDTO> {

    /**
     * 订单唯一性校验
     *
     * @param cancelPayDTO     被校验对象
     */
    public PreAuthBO validateUniqueOrder(CancelPayDTO cancelPayDTO, PreAuthRepository preAuthRepository){
        PayBaseBO order = preAuthRepository.checkIdempotent(cancelPayDTO.getRequestBizNo(),
                cancelPayDTO.getRequestOrderNo(),cancelPayDTO.getRequestSystem());
        if(order != null){
            log.error("订单已存在:{},{}",cancelPayDTO.getRequestBizNo(),cancelPayDTO.getRequestOrderNo());
            throw new PayCoreBizException(PayCoreErrorCode.ORDER_EXITS);
        }
        //查询原单信息
        PreAuthBO preAuthBO = preAuthRepository.getPreAuthByOrig(cancelPayDTO.getOrigPayNo(),
                cancelPayDTO.getOrigRequestDate(), cancelPayDTO.getOrigRequestBizNo(),
                cancelPayDTO.getOrigRequestOrderNo(), cancelPayDTO.getOrigRequestSystem());
        if (preAuthBO == null){
            log.error("预授权单不存在 撤销请求参数:{}", cancelPayDTO);
            throw new PayCoreBizException(PayCoreErrorCode.PRE_AUTH_ORDER_NO_EXIST);
        }
        if (!PayStatusEnums.SUCCESS.getCode().equals(preAuthBO.getStatus())){
            log.error("预授权订单状态不成功 不能撤销 支付单号:{} 状态:{}",preAuthBO.getPayNo(), preAuthBO.getStatus());
            throw new PayCoreBizException(PayCoreErrorCode.PRE_AUTH_ORDER_NO_SUC);
        }
        if (preAuthBO.getAmt() < preAuthBO.getDealAmt() + cancelPayDTO.getAmt()){
            log.error("预授权撤销金额大于可撤销金额 订单号:{} 预授权总金额:{} 已处理金额:{} 准备撤销金额:{}", preAuthBO.getPayNo(),
                    preAuthBO.getAmt(), preAuthBO.getDealAmt(), cancelPayDTO.getAmt());
            throw new PayCoreBizException(PayCoreErrorCode.OVERRUN_CANCEL_AMOUNT);
        }
        return preAuthBO;
    }
}
